import qs from 'query-string'
import { HashRouter } from 'react-router-dom'
import { postAdminLoginApi } from '../../api/auth'
import { commonLS, toLoginWithFrom } from '../../utils/common'
import { DELETE_USERINFO_TYPE, UPDATE_USERINFO_TYPE } from './types'

const router = new HashRouter()
const actions = {
  handleLoginChange: (params) => async (dispatch) => {
    try {
      const {
        adminname, token, checkedkeys, role,
      } = await postAdminLoginApi(params)
      dispatch({
        type: UPDATE_USERINFO_TYPE,
        payload: {
          adminname, token, checkedkeys, role,
        },
      })
      commonLS.put('adminname', adminname)
      commonLS.put('token', token)
      commonLS.put('checkedkeys', checkedkeys)
      commonLS.put('role', role)
      router.history.replace(qs.parse(router.history.location.search)?.from || '/general')
    } catch (err) {
      console.log(err)
    }
  },
  handleLoginOut: () => {
    commonLS.del('adminname')
    commonLS.del('token')
    commonLS.del('role')
    commonLS.del('checkedKeys')
    toLoginWithFrom(router)
    return {
      type: DELETE_USERINFO_TYPE,
    }
  },
}

export default actions;
